package binarysearch;

import java.util.Arrays;

public class BinarySearchText {
    public static void main(String[] args) {
        int arr[]={30,20,50,10,80,9,7,12,100,40,8};
        int search=-40;
        Arrays.sort(arr);
        System.out.println("数组排序后为:"+Arrays.toString(arr));
        int index=binarySearch(arr,search);
        if(index!=-1){
            System.out.println(search+"元素位置的下标为:"+binarySearch(arr,search));
        }else{
            System.out.println("该数组不存在元素"+search);
        }
    }
    public static int binarySearch(int[] arr,int search){
        int left=0;
        int right=arr.length-1;
        while(left <= right){
            int mid=(left+right)/2;
            if(search > arr[mid]){
                left = mid+1;
            }else if (search < arr[mid]) {
                right = mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
